Conditions | 12 |
Total Lines | 70 |
Code Lines | 62 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like index.ts ➔ readMd often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | import type { PathLike } from "fs" |
||
64 | |||
65 | async function readMd(path: PathLike) { |
||
66 | const reader = createLineReader(path) |
||
67 | //@ts-expect-error |
||
68 | , $return: { |
||
69 | //@ts-expect-error |
||
70 | "": string[] |
||
71 | [x: string]: Record<string, string> //string[] | boolean |
||
72 | } = {"": [] as string[]} |
||
73 | |||
74 | let headers: undefined|string[] |
||
75 | |||
76 | for await (const line of reader) { |
||
77 | if (!line.match(/^\|([^|]*\|)+$/)) { |
||
78 | headers = undefined |
||
79 | continue |
||
80 | } |
||
81 | |||
82 | if (headers === undefined) { |
||
83 | headers = line.split(/\s*\|\s*/) |
||
84 | headers.shift() |
||
85 | headers.length-- |
||
86 | |||
87 | const {length} = headers |
||
88 | for (let i = 0; i < length; i++) { |
||
89 | const header = headers[i] |
||
90 | |||
91 | if (!header) |
||
92 | continue |
||
93 | |||
94 | $return[header] = {} |
||
95 | } |
||
96 | |||
97 | continue |
||
98 | } |
||
99 | |||
100 | if (line.match(/^\|(\s*\-+\s*\|)+$/)) |
||
101 | continue |
||
102 | |||
103 | const cellParser = /[^\|]+/g |
||
104 | |||
105 | let i = -1 |
||
106 | , key: string |
||
107 | , cell: string|undefined |
||
108 | |||
109 | while (cell = cellParser.exec(line)?.[0]) { |
||
110 | i++ |
||
111 | |||
112 | const trimmed = cell |
||
113 | .replace(/(^ +| +$)/g, '') |
||
114 | .replace(" ", " ") |
||
115 | .replace(" ", "\t") |
||
116 | |||
117 | if (i === 0) { |
||
118 | if (!trimmed) |
||
119 | break |
||
120 | |||
121 | key = trimmed |
||
122 | $return[""].push(trimmed) |
||
123 | continue |
||
124 | } |
||
125 | |||
126 | if (!trimmed) |
||
127 | continue |
||
128 | |||
129 | $return[headers[i]][key!] = trimmed |
||
130 | } |
||
131 | } |
||
132 | |||
133 | return $return |
||
134 | } |
||
135 |